package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;

    /*
    * 新增菜品和对应的口味
    * 菜品：口味 = 1：n
    * */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        // 声明一个菜品对象
        Dish dish = new Dish();
        // 将dishDTO中的属性拷贝到dish中
        BeanUtils.copyProperties(dishDTO, dish);
        //设置当前用户创建时间与修改时间
        dish.setCreateTime(new Date());
        dish.setUpdateTime(new Date());
        //设置当前用户创建人id与修改人id
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //向菜品表插入一条数据
        dishMapper.insert(dish);

        //获取插入的菜品id
        Long dishId = dish.getId();

        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //批量插入口味
            dishFlavorMapper.insertBatch(flavors);

        }

    }

    /*
    * 菜品分页查询
    * */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /*
    * 菜品批量删除
    * */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除--是否在启售状态（不是才可以删除）
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品正在启售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除--是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的数据

//            dishMapper.deleteById(id);
            dishMapper.deleteBatchIds(ids);
            //删除菜品表对应的口味数据
            dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().in("dish_id", ids));


    }

    /*
     * 根据id查询菜品和对应的口味数据
     * */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //根据id查询口味数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(new QueryWrapper<DishFlavor>().eq("dish_id", id));
        //组合返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /*
     * 修改菜品和对应的口味数据
     * */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setUpdateTime(new Date());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //修改菜品基本信息
        dishMapper.updateById(dish);
        //删除口味数据
        dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().eq("dish_id", dishDTO.getId()));
        //添加口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
//        List<Dish> dishList = dishMapper.list(dish);
        List<Dish> dishList = dishMapper.selectList(new QueryWrapper<Dish>().eq("category_id", dish.getCategoryId()).eq("status", 1));
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
//            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            List<DishFlavor> flavors = dishFlavorMapper.selectList(new QueryWrapper<DishFlavor>().eq("dish_id", d.getId()));
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .updateTime(new Date())
                .updateUser(BaseContext.getCurrentId())
                .build();
        update(dish,new UpdateWrapper<Dish>().eq("id",dish.getId()));
    }

}
